package com.test.hand.client;

import com.test.hand.message.*;
import com.test.hand.protocol.MessageCodecSharable;
import com.test.hand.protocol.ProtocolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class ChatClient {
    public static void main(String[] args) {
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.INFO);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);
        AtomicBoolean LOGIN = new AtomicBoolean(false);
        AtomicBoolean EXIT = new AtomicBoolean(false);
        // 开始配置客户端
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                /*
                ChannelInitializer只负责初始化，不会参与pipeline当中的调用逻辑，所以，
                书写的处理逻辑都在ChannelInitializer匿名类重写的方法的initChannel中进行书写
                 */
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        // 帧解码器
                        ch.pipeline().addLast(new ProtocolFrameDecoder());
                        ch.pipeline().addLast(LOGGING_HANDLER);
                        ch.pipeline().addLast(MESSAGE_CODEC);
                        // 3s的心跳包
                        ch.pipeline().addLast(
                                // 设置一个检测器，关注读事件，如果一个channel没有写东西，服务端就没有读取到东西
                                new IdleStateHandler(0, 3, 0));
                        // 添加双向处理器，处理检测器触发的事件
                        ch.pipeline().addLast(new ChannelDuplexHandler() {
                            @Override
                            public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                                if (evt instanceof IdleStateEvent) {
                                    IdleStateEvent event = (IdleStateEvent) evt;
                                    // 向服务器发送心跳包
                                    if (event.state() == IdleState.WRITER_IDLE) {
                                        log.debug("Heartbeat-3s");
                                        ctx.writeAndFlush(new PingMessage());
                                    }
                                }
                            }
                        });
                        ch.pipeline().addLast("client handler", new ChannelInboundHandlerAdapter() {
                            // 读取到数据的处理
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                log.info("client received: {}", msg);

                                // 处理登录逻辑
                                if (msg instanceof LoginResponseMessage) {
                                    LoginResponseMessage loginMsg = (LoginResponseMessage) msg;
                                    if (loginMsg.isSuccess()) {
                                        LOGIN.set(true);
                                    }
                                    // 取消再登录线程的阻塞
                                    WAIT_FOR_LOGIN.countDown();
                                }
                            }

                            /*
                            如果你在思考为什么channelActive不放在ChannelInitializer这里重写，因为ChannelInitializer
                            只是负责初始化，不负责链接操作，所以，需要添加到pipeline中去执行
                             */
                            // 连接成功的active处理
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                new Thread(() -> {
                                    Scanner scanner = new Scanner(System.in);
                                    System.out.println("请输入用户名");
                                    String username = scanner.nextLine();
                                    System.out.println("请输入密码");
                                    String password = scanner.nextLine();
                                    LoginRequestMessage login = new LoginRequestMessage(username, password);
                                    // 发出消息
                                    ctx.writeAndFlush(login);
                                    // 阻塞住
                                    try {
                                        WAIT_FOR_LOGIN.await();
                                        log.debug("登录处理完毕");
                                    } catch (InterruptedException e) {
                                        throw new RuntimeException(e);
                                    }
                                    // 如果没有登录成功
                                    if (!LOGIN.get()) {
                                        ctx.channel().close();
                                        return;
                                    }

                                    // 执行业务
                                    while (true) {
                                        System.out.println("==================================");
                                        System.out.println("send [username] [content]");
                                        System.out.println("gsend [group name] [content]");
                                        System.out.println("gcreate [group name] [m1,m2,m3...]");
                                        System.out.println("gmembers [group name]");
                                        System.out.println("gjoin [group name]");
                                        System.out.println("gquit [group name]");
                                        System.out.println("quit");
                                        System.out.println("==================================");
                                        String command = null;
                                        try {
                                            command = scanner.nextLine();
                                        } catch (Exception e) {
                                            break;
                                        }
                                        if (EXIT.get()) {
                                            return;
                                        }
                                        String[] s = command.split(" ");
                                        switch (s[0]) {
                                            case "send":
                                                ctx.writeAndFlush(new ChatRequestMessage(username, s[1], s[2]));
                                                break;
                                            case "gsend":
                                                ctx.writeAndFlush(new GroupChatRequestMessage(username, s[1], s[2]));
                                                break;
                                            case "gcreate":
                                                Set<String> set = new HashSet<>(Arrays.asList(s[2].split(",")));
                                                set.add(username); // 加入自己
                                                ctx.writeAndFlush(new GroupCreateRequestMessage(s[1], set));
                                                break;
                                            case "gmembers":
                                                ctx.writeAndFlush(new GroupMembersRequestMessage(s[1]));
                                                break;
                                            case "gjoin":
                                                ctx.writeAndFlush(new GroupJoinRequestMessage(username, s[1]));
                                                break;
                                            case "gquit":
                                                ctx.writeAndFlush(new GroupQuitRequestMessage(username, s[1]));
                                                break;
                                            case "quit":
                                                ctx.channel().close();
                                                return;
                                        }
                                    }

                                }, "system in").start();
                            }
                        });
                    }
                });
        try {
            Channel channel = bootstrap.connect("localhost", 8080).sync().channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭group，正常结束
            group.shutdownGracefully();
        }
    }
}
